package cz.muni.fi.pb138.avradiation.DB;

/**
 *
 * @author Andrej Kuročenko <kurochenko@gmail.com>
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBUtils {
    private static final Logger logger =
            Logger.getLogger(DBUtils.class.getName());
    /**
     * Gets ID from resultset
     *
     * @param keys
     * @return id contained in resultset
     * @throws SQLException
     */
    public static Long getId(ResultSet keys) throws SQLException {
        if (keys == null) {
            throw new IllegalArgumentException("Parameter [keys] is null.");
        }
        if (keys.getMetaData().getColumnCount() != 1) {
            logger.log(Level.SEVERE, "Given ResultSet contains "
                    + "more columns");
            throw new IllegalArgumentException("Given ResultSet contains "
                    + "more columns");
        }
        if (keys.next()) {
            Long result = keys.getLong(1);
            if (keys.next()) {
                logger.log(Level.SEVERE, "Given ResultSet contains "
                        + "more rows");
                throw new IllegalArgumentException("Given ResultSet contains "
                        + "more rows");
            }
            return result;
        } else {
            logger.log(Level.SEVERE, "Given ResultSet contain "
                    + "no rows");
            throw new IllegalArgumentException("Given ResultSet contain "
                    + "no rows");
        }
    }
    
    /**
     * Closes connection if exists
     * 
     * @param conn 
     */
    public static void closeConnection(Connection conn) {
        if (conn == null) {
            throw new IllegalArgumentException("Connection is null.");
        }
        try {
            conn.close();
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Error when closing connection"
                    , ex.getMessage());
            throw new RuntimeException("Failed to close connection "
                    + ex.getMessage());
        }
    }
}